<template>
  <div class="form-rules-container layout-pd" style="text-align: left">
    <el-form :model="queryUserForm" inline>
      <el-form-item label="用户名" >
        <el-input v-model="queryUserForm.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="queryUserForm.phone" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="角色">
        <el-select v-model="queryUserForm.roles" placeholder="选择角色" style="width:200px">
          <el-option label="管理员" value="1"></el-option>
          <el-option label="客服" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item >
        <el-button type="primary" @click="userSearch">搜索</el-button>
        <el-button>重置</el-button>
      </el-form-item>
    </el-form>
    <el-row>
      <el-col :span="24">
        <el-button type="primary" @click="handleOpen">新增</el-button>
      </el-col>
    </el-row>
    <el-table :data="tableData">
      <el-table-column label="ID" prop="id"></el-table-column>
      <el-table-column label="用户名" prop="username"></el-table-column>
      <el-table-column label="手机号" prop="phone"></el-table-column>
      <el-table-column label="角色" prop="roleName">
        <template #default="scope">
          {{roleName(scope.row.roleList)}}
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status">
        <template #default="scope">
          <el-switch v-model="scope.row.status"
                     active-value="1"
                     inactive-value="0"
                     @change="changeStatus(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="120">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="handleOpen(scope.row)" >修改</el-button>
          <el-button link type="primary" size="small" @click="delUser(scope.row.id)">删除</el-button>
          <el-button link type="primary" size="small" @click="handleOpenPass(scope.row)">重置密码</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
        v-model="dialogVisible"
        title="编辑用户"
        width="50%"
        :before-close="handleClose"
    >
      <el-form :model="userForm" inline ref="userFormDataRef" label-width="120" :rules="rules">
        <el-row>
          <el-col :span="userForm.id?24:12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="userForm.username" placeholder="填写角色名称" style="width: 100%;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="!userForm.id">
            <el-form-item label="登录密码" prop="password">
              <el-input type="password" show-password v-model="userForm.password" placeholder="填写登录密码"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="性别" >
              <el-radio value="1" v-model="userForm.sex">男</el-radio>
              <el-radio value="0" v-model="userForm.sex">女</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号">
              <el-input v-model="userForm.phone" placeholder="填写手机号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="用户角色">
              <el-select v-model="userForm.roles" multiple placeholder="选择角色" style="width:200px">
                <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
			<span class="dialog-footer">
				<el-button @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" @click="submitForm">
				提交
				</el-button>
			</span>
      </template>
    </el-dialog>
    <el-dialog
        v-model="dialogUpdateVisible"
        title="修改密码"
        :before-close="handleClosePass"
        style="width: 30%;"
    >
      <el-form :model="updatePwdForm" inline ref="passwordFormDataRef" label-width="120" >
        <el-form-item label="新密码">
          <el-input v-model="updatePwdForm.newPassWord" placeholder="输入新密码"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
			<span class="dialog-footer">
				<el-button @click="dialogUpdateVisible = false">取消</el-button>
				<el-button type="primary" @click="submitPassForm">
				提交
				</el-button>
			</span>
      </template>
    </el-dialog>
  </div>
</template>

<script>

import {getCurrentInstance, onMounted, reactive, ref, toRefs} from "vue";
import {ElMessage} from "element-plus";

export default {
  setup() {
    const axios = getCurrentInstance().appContext.config.globalProperties.$axios;
    const roleList = ref([])
    const state = reactive({
      queryUserForm: {},
      tableData: [],
      userForm: {},
      updatePwdForm: {},
      currentPage: 1,
      pageSize: 5,
      total: 0,
      dialogVisible: false,
      dialogUpdateVisible: false
    })
    // 数据验证
    const rules = ref({
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
      ]
    })
    // 打开编辑窗口
    const handleOpen = (row) => {
      state.dialogVisible = true
      if (row.id) {
        state.userForm = row
      } else {
        state.userForm = {}
      }
    }
    // 关闭编辑窗口
    const handleClose = () => {
      state.dialogVisible = false
      state.userForm = {}
    }
    // 打开重置密码窗口
    const handleOpenPass = (row) => {
      console.log(row)
      state.updatePwdForm = row
      state.dialogUpdateVisible = true
    }
    // 关闭重置密码窗口
    const handleClosePass = () => {
      state.dialogUpdateVisible = false
    }
    // 用户搜索
    const userSearch = async () => {
      let res = await axios.post('/admin/5/1', state.queryUserForm);
      state.tableData = res.data.data.records;
    }
    // 用户角色名称处理
    const roleName = (roleList) => {
      let roleName = ''
      if (roleList && roleList.length > 0) {
        roleList.forEach(item => {
          roleName += item.name + ','
        })
      }
      return roleName.substring(0, roleName.length - 1)
    }
    // 更新用户状态
    const changeStatus = async (row) => {
      await axios.get(`/admin/switchStatus/${row.id}/${row.status}`)
      ElMessage.success('修改成功')
      await userSearch()
    }
    // 删除用户
    const delUser = async (id) => {
      await axios.delete(`/admin/${id}`)
      ElMessage.success('删除成功')
      await userSearch()
    }
    // 编辑用户
    const submitForm = async () => {
      // 判断是修改还是新增
      if (state.userForm.id) {
        await axios.put('/admin', state.userForm)
        ElMessage.success("修改成功")
        state.dialogVisible = false
        await userSearch()
      } else {
        let res = await axios.post('/admin/add', state.userForm)
        if (res.data.code === "1") {
          ElMessage.success("新增成功")
          state.dialogVisible = false
          await userSearch()
        } else {
          ElMessage.error(res.msg);
        }
      }
    }
    // 重置密码
    const submitPassForm = async () => {
      console.log("请求后台提交数据")
      await axios.put(`/admin/resetPass/${state.updatePwdForm.id}`, {
        password: state.updatePwdForm.newPassWord
      })
      ElMessage.success("修改成功")
      state.dialogUpdateVisible = false
    }
    // 获取角色列表
    const getRoles = async () => {
      let res = await axios.get('/role/getAllRoles')
      roleList.value = res.data.data
    }
    onMounted(() => {
      userSearch()
      getRoles()
    })
    return {
      ...toRefs(state),
      handleOpen,
      handleClose,
      handleOpenPass,
      handleClosePass,
      changeStatus,
      roleList,
      userSearch,
      roleName,
      delUser,
      submitForm,
      submitPassForm,
      rules
    }
  }
}
</script>
